package service

import "gitee.com/gopher2011/mall/app/dao"

// 全局公开对象
var SmsCoupon = smsCouponService{}

// 私有对象，所有的方法都绑定到这个结构体上。

type smsCouponService struct{}

// 只要输入 dao.SmsCouponParam 的 PublishCount 参数即可
func (p *smsCouponService) Create(s dao.SmsCouponParam) (int64, error) {
	l := dao.SmsCouponParam{
		Count:        s.PublishCount,
		UseCount:     0,
		ReceiveCount: 0,
	}
	//插入优惠券表
	count, err := dao.SmsCouponDao.Insert(l)
	if err != nil {
		return count, err
	}
	//插入优惠券和商品关系表
	if s.UseType == 2 {
		for _, v := range s.SmsCouponProductRelation {
			v.CouponId = s.Id
			res, err := dao.SmsCouponProductRelationDao.Insert(v)
			if err != nil {
				return res, err
			}

		}
	}
	//插入优惠券和商品分类关系表
	if s.UseType == 1 {
		for _, v := range s.SmsCouponProductCategoryRelation {
			v.CouponId = s.Id
			res, err := dao.SmsCouponProductCategoryRelationDao.Insert(v)
			if err != nil {
				return res, err
			}

		}
	}
	return count, nil
}

func (p *smsCouponService) Delete(id int64) (int64, error) {
	//删除优惠券
	res, err := dao.SmsCouponDao.DeleteById(id)
	if err != nil {
		return res, err
	}
	//删除商品关联
	p.deleteProductRelation(id)
	//删除商品分类关联
	p.deleteProductCategoryRelation(id)
	return res, nil
}

func (p *smsCouponService) deleteProductCategoryRelation(id int64) (int64, error) {
	//删除优惠券
	res, err := dao.SmsCouponProductCategoryRelationDao.DeleteById(id)
	if err != nil {
		return res, err
	}
	return res, nil
}

func (p *smsCouponService) deleteProductRelation(id int64) (int64, error) {
	//删除优惠券
	res, err := dao.SmsCouponProductRelationDao.DeleteById(id)
	if err != nil {
		return res, err
	}
	return res, nil
}

func (p *smsCouponService) Update(id int64, u dao.SmsCouponParam) (int64, error) {
	u.Id = id
	res, err := dao.SmsCouponDao.UpdateById(u)
	if err != nil {
		return res, err
	}
	//删除后插入优惠券和商品关系表
	if u.UseType == 2 {
		for _, v := range u.SmsCouponProductRelation {
			v.CouponId = u.Id
			p.deleteProductRelation(id)
			res, err := dao.SmsCouponProductRelationDao.Insert(v)
			if err != nil {
				return res, err
			}
		}
	}
	//删除后插入优惠券和商品分类关系表
	if u.UseType == 1 {
		for _, v := range u.SmsCouponProductCategoryRelation {
			v.CouponId = u.Id
			p.deleteProductCategoryRelation(id)
			res, err := dao.SmsCouponProductCategoryRelationDao.Insert(v)
			if err != nil {
				return res, err
			}

		}
	}
	return res, nil
}

func (p *smsCouponService) List(s dao.SmsCouponList) ([]dao.SmsCoupon, error) {
	s.PageNum = (s.PageNum - 1) * s.PageSize
	return dao.SmsCouponDao.List(s)
}

func (p *smsCouponService) GetItem(id int64) (dao.SmsCouponParam, error) {
	return dao.SmsCouponDao.SelectById(id)
}
